package com.youbug.recreation.websocket;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.youbug.system.entity.User;
import com.youbug.recreation.config.TankConstant;
import com.youbug.recreation.config.TankRoomHolder;
import com.youbug.recreation.entity.GamePlayer;
import com.youbug.recreation.service.IGamePlayerService;
import com.youbug.system.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.util.ObjectUtils;


/**
 * @author websocket服务
 */
@ServerEndpoint(value = "/tankOnline/{roomId}/{userId}")
@Component
public class TankOnlineWebSocket {

    private static final Logger logger = LoggerFactory.getLogger(TankOnlineWebSocket.class);

    private static IUserService userService;
    private static IGamePlayerService gamePlayerService;

    @Autowired
    public void setService(IUserService userService, IGamePlayerService gamePlayerService) {
        TankOnlineWebSocket.userService = userService;
        TankOnlineWebSocket.gamePlayerService = gamePlayerService;
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("roomId") Long roomId, @PathParam("userId") Long userId) {

        Map<Long, GamePlayer> gameRoom = TankRoomHolder.roomHolder.get(roomId);

        if(ObjectUtils.isEmpty(gameRoom)){
            gameRoom =  new HashMap<>();
            TankRoomHolder.roomHolder.put(roomId, gameRoom);
        }

        GamePlayer player = gameRoom.get(userId);

        if(!ObjectUtils.isEmpty(player)){
            try {
                session.getBasicRemote().sendText("{\"type\":\"msg\",\"content\":\"该用户已经在房间中，请尝试其他房间或者切换用户\"}");
            } catch (IOException e) {
                throw new RuntimeException(userId + "该用户已经在房间中，请尝试其他房间或者切换用户");
            }
        }

        QueryWrapper<User> userWp = new QueryWrapper<User>().eq("id", userId);

        userWp.select("username","nick_name");

        User userDb = userService.getOne(userWp);

        GamePlayer gamePlayer = new GamePlayer();
        gamePlayer.setRoomId(roomId);
        gamePlayer.setGameName(TankConstant.TANK);
        gamePlayer.setUserId(userId);
        gamePlayer.setUsername(userDb.getUsername());
        gamePlayer.setNickName(userDb.getNickName());
        gamePlayer.setSession(session);
        gameRoom.put(userId, gamePlayer);
      //  gamePlayerService.save(gamePlayer);
    }

    @OnMessage
    public void onMessage(String message, Session session, @PathParam("roomId") Long roomId,
                          @PathParam("userId") Long userId) throws IOException {

        Map<Long, GamePlayer> longGamePlayerMap = TankRoomHolder.roomHolder.get(roomId);

        longGamePlayerMap.forEach((tempUserId, plyer) -> {

            if(!plyer.getUserId().equals(userId)){
                try {
                    plyer.getSession().getBasicRemote().sendText(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session, @PathParam("roomId") Long roomId, @PathParam("userId") Long userId) {
        Map<Long, GamePlayer> gamePlayerMap = TankRoomHolder.roomHolder.get(roomId);

        if(!ObjectUtils.isEmpty(gamePlayerMap)){
            gamePlayerMap.remove(userId);
        }
    }

    @OnError
    public void onError(Session session, Throwable error, @PathParam("roomId") Long roomId, @PathParam("userId") Long userId) throws IOException {
        Map<Long, GamePlayer> gamePlayerMap = TankRoomHolder.roomHolder.get(roomId);

        if(!ObjectUtils.isEmpty(gamePlayerMap)){
            gamePlayerMap.remove(userId);
        }
        logger.error(error.getMessage());
    }
}
